﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

using ClientLib;

namespace JigsawAdmin.SubForms.Security
{
    public partial class Roles : Form
    {
        TreeNode _selectednode;
        ClientUtil _cutil;
        JsvcEnc.EncSoapXml xmlsvc;
        ContextMenu ctxmRoles;

        public Roles(ClientUtil cUtil)
        {
            InitializeComponent();

            _cutil = cUtil;
            xmlsvc = new JsvcEnc.EncSoapXml();
            xmlsvc.Url = _cutil.ServiceURL;

            // set up folder images for treeview
            ImageList apiTreeList = new ImageList();
            apiTreeList.Images.Add(Image.FromFile("../../Images/Folder.png"));
            apiTreeList.Images.Add(Image.FromFile("../../Images/Node.png"));
            apiTreeList.Images.Add(Image.FromFile("../../Images/Rootfolder.png"));

            ctxmRoles = new ContextMenu();
            MenuItem mnuMethods = new MenuItem("Role Methods");
            MenuItem mnuGroups = new MenuItem("Role Groups");
            ctxmRoles.MenuItems.Add(mnuMethods);
            ctxmRoles.MenuItems.Add(mnuGroups);
            mnuMethods.Click += new EventHandler(mnuMethods_Click);
            mnuGroups.Click += new EventHandler(mnuGroups_Click);

            trvRoles.ImageList = apiTreeList;
            trvRoles.ImageIndex = 0;
            trvRoles.SelectedImageIndex = 1;
        }

        /// <summary>
        /// 
        /// </summary>
        private void mnuMethods_Click(object sender, EventArgs e)
        {
            RoleTreeNode selectedTag = (RoleTreeNode)_selectednode.Tag;
            string roleID = selectedTag.GID;

            // show method form for selected role
            RoleMethods rolemeth = new RoleMethods();
            rolemeth.Show();
        }

        /// <summary>
        /// 
        /// </summary>
        private void mnuGroups_Click(object sender, EventArgs e)
        {
            RoleTreeNode selectedTag = (RoleTreeNode)_selectednode.Tag;
            string roleID = selectedTag.GID;

            // show method form for selected role
            RoleGroups rolegrp = new RoleGroups();
            rolegrp.Show();
        }

        /// <summary>
        /// 
        /// </summary>
        private bool ValidateData()
        {
            bool isValid = true;

            if (txtRoleName.Text == "") isValid = false;
            if (txtDescription.Text == "") isValid = false;

            return isValid;
        }

        /// <summary>
        /// 
        /// </summary>
        private void Roles_Shown(object sender, EventArgs e)
        {
            try
            {
                PopulateRoleTree();
            }
            catch (Exception ex)
            {
                ErrorUtil eutil = new ErrorUtil();
                eutil.LogException(_cutil.UserID, "Roles Roles_Shown", "", ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void TreeEvents()
        {
            switch (_selectednode.Level)
            {
                case 0:
                    // root node level - do nothing
                    break;

                case 1:
                    // role level, get role versions
                    PopulateRoleVersions();

                    break;

                case 2:
                    // not used - do nothing
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void PopulateRoleTree()
        {
            // populate the top level of the tree
            Dictionary<string, string> paramList = new Dictionary<string, string>();

            string encryptedinput = _cutil.BuildMessageXML("SystemAdmin.GetAllRoles.Base", paramList, true);
            string results = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput);

            EncryptUtil eutil = new EncryptUtil();
            _cutil.ParseResponseMessage(eutil.DecryptString2(results, _cutil.SymmKey));

            if (_cutil.ResponseCode == "Success")
            {
                string tmpdata = _cutil.Result;
                tmpdata = tmpdata.Replace("<![CDATA[", "");
                tmpdata = tmpdata.Replace("]]>", "");

                StringReader sr = new StringReader(tmpdata);
                DataTable rolelist = new DataTable();
                rolelist.ReadXml(sr);

                if (rolelist.Rows.Count > 0)
                {
                    trvRoles.BeginUpdate();
                    trvRoles.Nodes.Clear();

                    // populate root node of API tree
                    RoleTreeNode rtnr = new RoleTreeNode();
                    rtnr.RoleName = "Jigsaw Roles";

                    TreeNode tnr = new TreeNode();
                    tnr.Text = "Jigsaw Roles";
                    tnr.ImageIndex = 2;
                    tnr.SelectedImageIndex = 2;
                    tnr.Tag = rtnr;

                    trvRoles.Nodes.Add(tnr);

                    // populate top level of API tree
                    foreach (DataRow dr in rolelist.Rows)
                    {
                        RoleTreeNode rtn = new RoleTreeNode();
                        rtn.RoleName = dr["RoleName"].ToString();
                        rtn.GID = dr["GlobalID"].ToString();

                        TreeNode tn = new TreeNode();
                        tn.Text = dr["RoleName"].ToString();
                        tn.ImageIndex = 1;
                        tn.SelectedImageIndex = 1;
                        tn.Tag = rtn;
                        tn.ContextMenu = ctxmRoles;

                        tnr.Nodes.Add(tn);
                    }

                    trvRoles.EndUpdate();
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        public void PopulateRoleVersions()
        {
            // get info from the selected tree node and tag object
            RoleTreeNode selectedTag = (RoleTreeNode)_selectednode.Tag;
            lblSelectedRole.Text = "Selected Role: " + selectedTag.RoleName;
            Dictionary<string, string> paramList = new Dictionary<string, string>();
            paramList.Add("RoleID", selectedTag.GID);

            string encryptedinput = _cutil.BuildMessageXML("SystemAdmin.GetRoleVersions.Base", paramList, true);
            string results = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput);

            EncryptUtil eutil = new EncryptUtil();
            _cutil.ParseResponseMessage(eutil.DecryptString2(results, _cutil.SymmKey));

            if (_cutil.ResponseCode == "Success")
            {
                string tmpdata = _cutil.Result;
                tmpdata = tmpdata.Replace("<![CDATA[", "");
                tmpdata = tmpdata.Replace("]]>", "");

                StringReader sr = new StringReader(tmpdata);
                DataTable verlist = new DataTable();
                verlist.ReadXml(sr);

                if (verlist.Rows.Count > 0)
                {
                    dgvRoleVersions.DataSource = verlist;
                    PopulateRoleForm();
                }
                else
                {
                    dgvRoleVersions.DataSource = null;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void PopulateRoleForm()
        {
            txtGlobalID.Text = dgvRoleVersions.SelectedRows[0].Cells["GlobalID"].Value.ToString();
            txtRoleName.Text = dgvRoleVersions.SelectedRows[0].Cells["RoleName"].Value.ToString();
            txtDescription.Text = dgvRoleVersions.SelectedRows[0].Cells["Description"].Value.ToString();

            btnSave.Enabled = true;
            btnDelete.Enabled = true;
            string rowstate = dgvRoleVersions.SelectedRows[0].Cells["RowState"].Value.ToString();
            if (rowstate != "Active")
            {
                btnRollback.Enabled = true;
                btnDelete.Enabled = false;
            }
            else
            {
                btnRollback.Enabled = false;
                btnDelete.Enabled = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void ClearRoleForm()
        {
            dgvRoleVersions.DataSource = null;
            txtGlobalID.Text = "";
            txtRoleName.Text = "";
            txtDescription.Text = "";
            dgvRoleMembers.DataSource = null;

            btnSave.Enabled = false;
            btnDelete.Enabled = false;
            btnRollback.Enabled = false;
        }

        /// <summary>
        /// 
        /// </summary>
        private void dgvRoleVersions_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            PopulateRoleForm();
        }

        /// <summary>
        /// 
        /// </summary>
        private void btnRollback_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                Dictionary<string, string> paramList = new Dictionary<string, string>();
                paramList.Add("GlobalID", txtGlobalID.Text);
                paramList.Add("RoleName", txtRoleName.Text);
                paramList.Add("Description", txtDescription.Text);

                // update existing record
                string encryptedinput = _cutil.BuildMessageXML("SystemAdmin.SaveAppRole.Base", paramList, true);
                string results = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput);

                EncryptUtil eutil = new EncryptUtil();
                _cutil.ParseResponseMessage(eutil.DecryptString2(results, _cutil.SymmKey));

                if (_cutil.ResponseCode == "Success")
                {
                    ClearRoleForm();
                    PopulateRoleTree();
                }
                else
                {
                    MessageBox.Show(_cutil.Result);
                }
            }
            else
            {
                MessageBox.Show("You must provide a value for all required fields.", "Data Validation");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void btnNew_Click(object sender, EventArgs e)
        {
            ClearRoleForm();
        }

        /// <summary>
        /// 
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                string action = "";
                Dictionary<string, string> paramList = new Dictionary<string, string>();
                paramList.Add("RoleName", txtRoleName.Text);
                paramList.Add("Description", txtDescription.Text);

                string encryptedinput = "";
                if (txtGlobalID.Text.Length > 0)
                {
                    // update existing record
                    paramList.Add("GlobalID", txtGlobalID.Text);
                    encryptedinput = _cutil.BuildMessageXML("SystemAdmin.SaveAppRole.Base", paramList, true);
                }
                else
                {
                    // insert new record
                    paramList.Add("GlobalID", _cutil.GetNewID());
                    encryptedinput = _cutil.BuildMessageXML("SystemAdmin.NewAppRole.Base", paramList, true);
                    action = "New";
                }

                string results = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput);

                EncryptUtil eutil = new EncryptUtil();
                _cutil.ParseResponseMessage(eutil.DecryptString2(results, _cutil.SymmKey));

                if (_cutil.ResponseCode == "Success")
                {
                    ClearRoleForm();
                    if (action == "New")
                    {
                        PopulateRoleTree();
                    }
                    else
                    {
                        TreeEvents();
                    }
                }
                else
                {
                    MessageBox.Show(_cutil.Result);
                }
            }
            else
            {
                MessageBox.Show("You must provide a value for all required fields.", "Data Validation");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                Dictionary<string, string> paramList = new Dictionary<string, string>();
                paramList.Add("GlobalID", txtGlobalID.Text);
                paramList.Add("RoleName", txtRoleName.Text);
                paramList.Add("Description", txtDescription.Text);
 
                // update existing record
                string encryptedinput = _cutil.BuildMessageXML("SystemAdmin.DeleteAppRole.Base", paramList, true);
                string results = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput);

                EncryptUtil eutil = new EncryptUtil();
                _cutil.ParseResponseMessage(eutil.DecryptString2(results, _cutil.SymmKey));

                if (_cutil.ResponseCode == "Success")
                {
                    ClearRoleForm();
                    PopulateRoleTree();
                }
                else
                {
                    MessageBox.Show(_cutil.Result);
                }
            }
            else
            {
                MessageBox.Show("You must provide a value for all required fields.", "Data Validation");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void trvRoles_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                ClearRoleForm();

                // assign the selected node
                _selectednode = trvRoles.SelectedNode;

                TreeEvents();
            }
            catch (Exception ex)
            {
                ErrorUtil eutil = new ErrorUtil();
                eutil.LogException(_cutil.UserID, "Roles trvRoles_AfterSelect", "", ex);
            }
        }

        private void txtRoleName_TextChanged(object sender, EventArgs e)
        {
            btnSave.Enabled = true;
        }
       
    }

    /// <summary>
    /// 
    /// </summary>
    public class RoleTreeNode
    {
        private string _rolename = "";
        private string _gid = "";

        public RoleTreeNode()
        {

        }

        public string RoleName
        {
            get { return _rolename; }
            set { _rolename = value; }
        }

        public string GID
        {
            get { return _gid; }
            set { _gid = value; }
        }
    }
}
